package dao

import (
	"mine-info-server/global"
	"mine-info-server/infra/database/mysql/common-context/message/po"
	"mine-info-server/interfaces/response"
)

/*
   @author:zhongyang
   @date:2023/4/12
   @description:站内信数据库操作
*/

type RemindMsgDao struct {
}

func NewRemindMsgDao() *RemindMsgDao {
	return &RemindMsgDao{}
}

func (r *RemindMsgDao) GetOne(msgId string) (*po.RemindMsg, error) {
	var res *po.RemindMsg
	err := global.GVA_DB.Where("msg_id = ?", msgId).First(&res).Error
	if err != nil {
		return nil, err
	}
	return res, nil
}

func (r *RemindMsgDao) ReadMsg(msgPO *po.RemindMsg) error {
	return global.GVA_DB.Model(&po.RemindMsg{}).Where("msg_id = ?", msgPO.MsgId).Update("is_read", msgPO.IsRead).Error
}

func (r *RemindMsgDao) IsMsgAllRead(userId string) (bool, error) {
	var msgId string
	err := global.GVA_DB.Model(&po.RemindMsg{}).Select("msg_id").Where("user_id = ? and is_read = ?", userId, 1).Limit(1).Find(&msgId).Error
	if err != nil {
		return false, err
	}
	// 所有消息已读返回true，否则返回false
	return msgId == "", nil
}

func (r *RemindMsgDao) GetMsgPageByUserId(page int, userId string, pageSize int, isRead int) (res []*response.MsgItemResponse, total int64, err error) {
	limit := pageSize
	offset := pageSize * (page - 1)
	// 创建db
	db := global.GVA_DB.Model(&po.RemindMsg{}).Where("user_id = ? and is_read = ?", userId, isRead)
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	err = db.Limit(limit).Offset(offset).Order("create_time DESC").Find(&res).Error
	return res, total, nil
}
